// pages/my/edit-user-info/edit-user-info.js
import WxValidate from '../../../utils/WxValidate'
const app = getApp()
const api = require('../../../utils/util')
Page({
    // 页面分享
    onShareAppMessage () {},
    // 分享朋友圈
    onShareTimeline () {},

  /**
   * 页面的初始数据
   */
  data: {

    form: {
      url: '',
      title: '',
      category: '',
      price: '',
      url1: '',
      introduction:'',
      sub_title:''
    },
    //   是否面议弹窗
    show:false,
    show1:false,
    value01:'否',
    columns: ['是', '否'],
    value02: '',
    category:[],
    id:'',
    disabled:''
  },
//   是否面议弹窗
showPop(e){
    let name = e.currentTarget.dataset.name;
    this.setData({
      [name]:true
    })
  },
  onConfirm(event) {
    const { picker, value, index } = event.detail;
    let { form } = this.data
    form.category = value
    this.setData({
      value01:value,
      form,
      show:false
    })
  },
  showPop(e){
    let name = e.currentTarget.dataset.name;
    this.setData({
      [name]:true
    })
  },
  onClose(){
    this.setData({
      show:false
    })
  },
  editHandle(e) {
    console.log(e);
    let {
      form
    } = this.data;
    form.introduction = e.detail.detail.html;
    this.setData({
      form
    });
},
editReadyHandle(e) {
  console.log('editReadyHandle',e)
    this.setData({
        editor: e.detail
    });

    this.data.editor.setContents({
        html:  this.htmlDecode(this.data.form.introduction)
    })
},
htmlDecode(str) {
  var s = '';
		if(str.length === 0) {
			return '';
		}
		s = str.replace(/&amp;/g, '&');
		s = s.replace(/&lt;/g,'<');
		s = s.replace(/&gt;/g,'>');
		s = s.replace(/&nbsp;/g,' ');
		s = s.replace(/&#39;/g,'\'');
		s = s.replace(/&quot;/g,'\"');
		return s;
},


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    let param = {
      id: options.id
    }
    this.setData({
      id: options.id
    })
    let {
      form
    } = this.data;
    api.product_show(param).then(function(res){
       form.url = app.globalData.siteUrl + res.data.url;
       form.title = res.data.title;
       form.price = res.data.price;
       form.category = res.data.category;
       form.url1 = res.data.url;
       form.introduction = res.data.introduction;
       form.sub_title = res.data.sub_title;
       that.setData({
         form,
         value02: res.data.category
       })
       console.log(res.data)
       if(res.data.is_discuss == '1'){
         that.setData({
           value01: '是'
         })
       }
    })

    this.initValidate();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this
    this.category(that)
  },

  showPop1(e){
    let name = e.currentTarget.dataset.name;
    this.setData({
      [name]:true
    })
  },
  onConfirm1(event) {
    const { picker, value, index } = event.detail;
    this.setData({
      value02:value,
      show1:false
    })
  },
  onClose1(){
    this.setData({
      show1:false
    })
  },
   //获取分类
   category(that){
    
    api.get_category().then(function(res){
      let cate = [];
    
      for(let i = 0; i< res.data.length; i++){
         for(let j = 0; j< res.data[i].list.length; j++){
          cate.push(res.data[i].list[j].title)
         }
      }
       console.log(cate)
       that.setData({
        category: cate
       })
    })
  },


  // 初始化表单验证
  initValidate() {
    //验证规则
    const rules = {
      url:{
        required: true
      },
      title: {
        required: true
      },
      category: {
        required: true
      },
      price: {
        required: true
      },
      
    };
    //验证规则提示语，若不传则调用默认的信息
    const messages = {
      url:{
        required: '请上传图片'
      },
      title: {
        required: '请输入标题'
      },
      category: {
        required: '请选择行业'
      },
       price: {
        required: '请输入价格'
      }
     
    };

    this.WxValidate = new WxValidate(rules, messages)
  },
  // 通用输入函数
  inputHandle(e) {
    let { name } = e.currentTarget.dataset;
    let value = e.detail;
    let form = this.data.form;
    form[name] = value.trim();
    this.setData({
      form
    });
  },

  // 提交
  submitHandle() {
    let {
      form
    } = this.data;
    // 表单验证
    if (!this.WxValidate.checkForm(this.data.form)) {
      const error = this.WxValidate.errorList[0];
      wx.showToast({
        title: error.msg,
        icon: 'none',
        image: '',
        duration: 1500,
        mask: false,
        success: (result)=>{
          
        },
        fail: ()=>{},
        complete: ()=>{}
      });
      return false
    }

    this.setData({
      disabled: 'disabled'
    })
    
    
    let param = {
      id: this.data.id,
      url: form.url1,
      title: form.title,
      category: this.data.value02,
      price: form.price,
      introduction: form.introduction,
      is_discuss: this.data.value01,
      sub_title: form.sub_title
    }
    api.edit_product(param).then(function(res){

      if(res.code == '0'){
        wx.showToast({
          title: '修改成功',
          success:function(){ 
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/serviced/serviced',
              });
             }, 2000)} 
        })
      }else{
        wx.showToast({
          title: '修改失败',
          icon:'error'
        })
      }
    })
  },

  afterRead(event) {
    const that = this;
    const { file } = event.detail;
    let {
      form
    } = this.data;
    var header = { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' };
    wx.uploadFile({
      url: app.globalData.uploadUrl, 
      filePath: file.url,
      name: 'file',
      header:header,
      formData: { user: 'test' },
      success(res) {
        var api_data = JSON.parse(res.data) 
        console.log(api_data.data.pic);
        // 上传完成需要更新 fileList
        form.url1 = api_data.data.pic;
      },
    });
    
    form.url = file.url;
    this.setData({
      form
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
